/*
 * @(#)SwiftRollingFileAppender.java   1.0  2021年6月29日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.core.log.appender;

import java.util.LinkedList;
import java.util.List;

import com.swift.util.type.TypeUtil;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.status.ErrorStatus;

/**
 * 添加说明 
 * @author zhengjiajin
 * @version 1.0 2021年6月29日
 */
public class SwiftRemoteAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    private Layout<ILoggingEvent> layout;
    //采用注册制,部份启动日志会丢失
    private static List<SwiftAppender> remoteAppenderList = new LinkedList<>();
    
    @Override
    public void start() {
        if (this.layout == null) {
            addStatus(new ErrorStatus("No layout set for the appender named \"" + name + "\".", this));
            return;
        }
        super.start();
    }
    
    /** 
     * @see ch.qos.logback.core.UnsynchronizedAppenderBase#append(java.lang.Object)
     */
    @Override
    protected void append(ILoggingEvent eventObject) {
        if(TypeUtil.isNull(remoteAppenderList)) return;
        String body = layout.doLayout(eventObject);
        for(SwiftAppender remoteAppender : remoteAppenderList) {
            try {
                remoteAppender.append(eventObject.getLevel(),body);
            }catch(Throwable e) {
                addStatus(new ErrorStatus("Failed to send event: " + body, this, e));
            }
        }
    }
    
    public static void addRemoteAppender(SwiftAppender swiftAppender) {
        remoteAppenderList.add(swiftAppender);
    }
    
    public Layout<ILoggingEvent> getLayout() {
        return layout;
    }

    public void setLayout(Layout<ILoggingEvent> layout) {
        this.layout = layout;
    }

}
